<?php

    $serv = new swoole_websocket_server("0.0.0.0", 9527);

    $redis = new Redis();
    $redis->connect('redis',6379);

    $serv->on('Open', function($server, $req) {
        echo "connection open: ".$req->fd . PHP_EOL;
    });

    $serv->on('Message', function($server, $frame) {

        global $redis;

        $data = json_decode($frame->data,true);

        // 管理员登录
        if ($data['action'] == 'login') {

            // 添加到在线列表
            $redis->hSet('online_admin',$data['token'],$frame->fd);
            echo "{$data['token']} login ".PHP_EOL;

            $server->push($frame->fd, json_encode($data));
        }

        // 发送通知给管理员
        if ( $data['action'] == 'notice' ) {

            $to = $data['to'];
            $msg = json_encode($data);

            // 发送给所有人
            if (empty($to)) {
                $ids = $redis->hGetAll('online_admin');

                foreach ($ids as $token => $id) {
                    $server->push($id, $msg);
                    echo "send notice $msg, to $token".PHP_EOL;
                }
            } else {
                $id = $redis->hGet('online_admin',$to);
                $server->push($id, $msg);

                echo "send notice $msg, to $to".PHP_EOL;
            }

            $server->push($frame->fd, 'ok');

        }

        // 打印当前在线管理员列表
        print_r($redis->hGetAll('online_admin'));

    });

    $serv->on('Close', function($server, $fd) {

        global $redis;
        $ids = $redis->hGetAll('online_admin');

        // 管理员下线
        foreach ($ids as $token => $id) {
            if ($fd == $id ){
                $redis->hDel('online_admin',$token);
                echo "$token left ".PHP_EOL;
            }
        }

        echo "connection close: ".$fd.PHP_EOL;
    });

    $serv->start();
